package com.lsh.airticket.service.imp;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.lsh.airticket.dao.UserDao;
import com.lsh.airticket.entity.User;
import com.lsh.airticket.exception.UserException;
import com.lsh.airticket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author lsh
 * @date 2021/2/13
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public User login(String username, String password) {
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            throw new UserException("用户名密码不能为空");
        }
        System.out.println(username);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userTel", username);
        map.put("userPass", password);
        List<User> users = userDao.findTbUserByCondition(map);
        if (users != null && users.size() >0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public int register(User user) {
        //随机生成 密钥
        String salt = RandomUtil.randomString(4);
        user.setUserSalt(salt);
        //利用md5加密
        user.setUserPass(DigestUtil.md5Hex(user.getUserPass() + salt));
        user.setUserCreatetime(new Date());
        int insert = userDao.insertTbUser(user);
        return insert;
    }

    /**
     * 验证手机号有没有注册。
     * @param userTel
     */
    @Override
    public void findUserByTel(String userTel) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userTel", userTel);
        List<User> users = userDao.findTbUserByCondition(map);
        if (users.size() > 0) {
            throw new UserException("改手机号已被注册。");
        }
    }

    @Override
    public User findTbUserById(Integer userId) {
        return userDao.findTbUserById(userId);
    }

    @Override
    public User findUserByPhone(String phone) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userTel", phone);
        List<User> list = userDao.findTbUserByCondition(map);
        if (list != null && list.size() != 1) {
            throw new UserException("账号存在");
        }
        return list.get(0);
    }
}
